# -*- coding: utf-8 -*-
"""
__mktime__ = '2019/4/14'
__author__ = 'Just'
__filename__ = 'comic'
"""
import json
import operator
from flask import g, jsonify
from app.libs.error_code import DeleteSuccess, Success, NotFoundException, ParameterException
from app.libs.redprint import Redprint
from app.libs.token_auth import auth
from app.model.comic import Comic
from app.model.comic_latest import ComicLatest
from app.model.user import User, db
from app.services.comic import ComicService
from app.validators.form import ComicSearchForm, ComicReadForm, DeleteMyComicForm
from app.viewmodel.comic import ComicDetailViewModel, ComicDetailCollection

api = Redprint('comic')


@api.route('/<int:cid>', methods=['GET'])
def one(cid):
    """获取某id漫画的基本数据"""
    comic = Comic.query.filter_by(cid=cid).first_or_404(msg='此漫画暂无', error_code=5000)
    comic.hide('description', 'area')
    return jsonify(comic)


@api.route('/<int:cid>/detail', methods=['GET'])
def detail(cid):
    """获取某id漫画的详细数据"""
    comic = Comic.query.filter_by(cid=cid).first_or_404(msg='此漫画暂无', error_code=5000)
    comic = ComicDetailViewModel(comic, comic.updates)
    return jsonify(comic)


@api.route('/hot', methods=['GET'])
def hot():
    """最近更新"""
    updates = ComicLatest.get_hot_midlist()
    midlist = [item['cid'] for item in updates]

    # mhlist = db.session.query(ManHua).filter(
    #     ManHua.status == 1,
    #     ManHua.mid.in_(midlist)
    #     ).all()

    comics = Comic.query.filter(
        Comic.status == 1,
        Comic.cid.in_(midlist)
        ).all()

    updates.sort(key=operator.attrgetter('cid'))
    comics.sort(key=operator.attrgetter('cid'))

    list_collection = list(zip(comics, updates))
    comic_collection = ComicDetailCollection()
    comic_collection.fill(list_collection)
    return jsonify(comic_collection)


@api.route('/search', methods=['POST'])
def search():
    """关键字搜索 ?q={}&start={}&count={}"""
    form = ComicSearchForm().validate_for_api()
    q = '%' + form.q.data + '%'
    start = form.start.data
    limit = form.limit.data
    comics = Comic.fuzzy_search(q, start, limit)
    return jsonify(comics)


@api.route('/my', methods=['GET'])
@auth.login_required
def my_comics():
    """获取我的漫画"""
    uid = g.user.uid
    user = User.query.filter_by(id=uid).first_or_404(msg="用户不存在", error_code=6001)
    comics = User.query.get(uid).comics.all()
    if not comics:
        raise NotFoundException(msg='暂无, 快去收藏吧', error_code=5004)
    res = {
        "comics": comics,
        "total": len(comics)
    }
    return jsonify(res)


@api.route('/my', methods=['DELETE'])
@auth.login_required
def remove_my_comic():
    """移除我的一本漫画"""
    uid = g.user.uid
    user = User.query.filter_by(id=uid).first_or_404(msg="用户不存在", error_code=6001)
    form = DeleteMyComicForm().validate_for_api()
    comics_id = form.comics.data
    user_comics_id = [item.id for item in user.comics.all()]
    if not user_comics_id:
        raise ParameterException(msg='这些主题记录已不存在了', error_code=5001)
    comics_id = list(set(comics_id) & set(user_comics_id)) # 交集
    with db.auto_commit():
        comics = Comic.query.filter(
            Comic.status == 1,
            Comic.cid.in_(comics_id)
        ).all()
        [user.comics.remove(comic) for comic in comics]
    return DeleteSuccess(msg="删除成功")


@api.route('/<int:cid>/my', methods=['POST'])
@auth.login_required
def add_my_comic(cid):
    """添加一本图书"""
    uid = g.user.uid
    user = User.query.filter_by(id=uid).first_or_404(msg="用户不存在", error_code=6001)
    comic = Comic.query.filter_by(cid=cid).first_or_404(msg='此漫画暂无', error_code=5000)
    if comic in user.comics.all():
        raise ParameterException(msg='已经在你的漫画架了', error_code=5000)
    with db.auto_commit():
        user.comics.add(comic)
    return Success(code=201, msg='添加成功')


@api.route('/<int:cid>/sections', methods=['GET'])
def sections(cid):
    """获取章节信息"""
    comic = Comic.query.filter_by(cid=cid).first_or_404(msg='此漫画暂无', error_code=5000)
    sections = comic.sections.all()
    if not sections:
        raise NotFoundException(msg='没有章节数据', error_code=5009)

    total = comic.sections.count()
    section_list = [section.hide('cid', 'id') for section in sections]
    section_list.sort(key=lambda x: x['sid'], reverse=False)
    res = {
      'cid': cid,
      'total': total,
      'sections': section_list
    }
    return jsonify(res)


@api.route('/content', methods=['POST'])
def content():
    """获取章节具体内容数据"""
    form = ComicReadForm().validate_for_api()
    comic_service = ComicService(cid=form.cid.data, sid=form.sid.data)
    comic_service.get_content()
    if comic_service.total is None:
        raise NotFoundException(msg='此章节暂无内容数据', error_code=5010)
    res = {
        'images': comic_service.images,
        'total': comic_service.total
    }
    return jsonify(res)
